/**
 * 五菱行车轨迹地图
 */
import React from 'react';
import {Modal, Button} from 'antd/lib/index';
import {Map, Polyline, Marker} from 'react-amap';

/**
 * 最多最小经纬度坐标
 * @type {number}
 */
let lon_max = 0;
let lon_min = 0;
let lat_max = 0;
let lat_min = 0;

class MapModel extends React.PureComponent {

  componentDidMount() {
    this.props.onRef(this);
  }

  state = {
    value1: '起',
    value2: '终',
    mapCenter: {longitude: 145, latitude: 30},    //初始定位到中国
    linePath: [],       //行车轨迹线路点集
    zoomSize: 10,//缩放等级（比例）

    //起点与终点
    markerPosition1: {},
    markerPosition2: {}
  };

  /**
   * 对接口数据进行处理
   * @param data
   */
  handleSetInterval = (data) => {
    let points = [];
    let p1 = [];
    let p2 = [];
    for (let i = 0; i < data.length; i++) {
      let lon = data[i].lon;
      let lat = data[i].lat;
      if (i === 0) {
        lon_max = lon;
        lon_min = lon;
        lat_max = lat;
        lat_min = lat;
        p1.push(this.bd_decrypt(lon, lat));
      } else {
        if (data[i].lon > lon_max) {
          lon_max = lon;
        }
        if (data[i].lon < lon_min) {
          lon_min = lon;
        }
        if (data[i].lat > lat_max) {
          lat_max = lat;
        }
        if (data[i].lat < lat_min) {
          lat_min = lat;
        }
        if (i === data.length - 1) {
          p2.push(this.bd_decrypt(lon, lat));
        }
      }
      points.push(this.bd_decrypt(lon, lat));
    }

    //计算右上角到左下角的2点直线距离
    //let p1 = [lon_min, lat_max];
    //let p2 = [lon_max, lat_min];
    let distance = this.getDistance(lat_max, lon_min, lat_min, lon_max) * 1000;
    //console.log(`对角线距离是：${distance}米。`);

    /**
     * 设置而大致的zoom比例,基于百度的区间调整的
     * @type {number}
     */
    let zz = 10;
    if (distance < 50) {
      zz = 16;
    } else if (distance > 50 && distance < 100) {
      zz = 16;
    } else if (distance > 100 && distance < 200) {
      zz = 15;
    } else if (distance > 200 && distance < 500) {
      zz = 15;
    } else if (distance > 500 && distance < 1000) {
      zz = 14;
    } else if (distance > 1000 && distance < 2000) {
      zz = 14;
    } else if (distance > 2000 && distance < 5000) {
      zz = 12;
    } else if (distance > 5000 && distance < 10000) {
      zz = 12;
    } else if (distance > 10000 && distance < 20000) {
      zz = 11;
    } else if (distance > 20000 && distance < 25000) {
      zz = 11;
    } else if (distance > 25000 && distance < 50000) {
      zz = 9;
    } else if (distance > 50000 && distance < 100000) {
      zz = 8;
    } else if (distance > 100000 && distance < 200000) {
      zz = 7;
    } else if (distance > 200000 && distance < 500000) {
      zz = 6;
    } else if (distance > 500000 && distance < 1000000) {
      zz = 5;
    } else if (distance > 1000000 && distance < 2000000) {
      zz = 5;
    }

    /** distance<200 解决求中心点误差导致的定位问题,直接定位起点为中心点 */
    if (distance < 200) {
      this.setState({
        linePath: points,
        mapCenter: {longitude: p1[0].longitude, latitude: p1[0].latitude},    //定位地图中心点
        zoomSize: zz,
        markerPosition1: {longitude: p1[0].longitude, latitude: p1[0].latitude},
        markerPosition2: {longitude: p2[0].longitude, latitude: p2[0].latitude}
      });
    } else {
      this.setState({
        linePath: points,
        mapCenter: {longitude: (lon_max + lon_min) / 2, latitude: (lat_max + lat_min) / 2},    //定位地图中心点
        zoomSize: zz,
        markerPosition1: {longitude: p1[0].longitude, latitude: p1[0].latitude},
        markerPosition2: {longitude: p2[0].longitude, latitude: p2[0].latitude}
      });
    }

  };

  /**
   * 百度坐标转高德坐标
   * @param lon
   * @param lat
   * @returns {{lng: number, lat: number}}
   */
  bd_decrypt = (lon, lat) => {
    let X_PI = Math.PI * 3000.0 / 180.0;
    let x = lon - 0.0065;
    let y = lat - 0.006;
    let z = Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y * X_PI);
    let theta = Math.atan2(y, x) - 0.000003 * Math.cos(x * X_PI);
    let gg_lng = z * Math.cos(theta);
    let gg_lat = z * Math.sin(theta);
    return {longitude: gg_lng, latitude: gg_lat};
  };

  /**
   * 地图弹框关闭,清理数据
   */
  onClose = () => {
    lon_max = 0;
    lon_min = 0;
    lat_max = 0;
    lat_min = 0;
    const {changeVisible} = this.props;
    changeVisible();
    this.setState({
      mapCenter: {longitude: 145, latitude: 30},    //初始定位到中国
      linePath: [],        //行车轨迹点
      zoomSize: 10,
      markerPosition1: {},
      markerPosition2: {}
    });
  };

  /**
   * 2点之间的距离
   * @param lat1 右上纬度
   * @param lng1 右上经度
   * @param lat2 左下纬度
   * @param lng2 左下经度
   * @returns {number} 距离（KM）
   */
  getDistance = (lat1, lng1, lat2, lng2) => {
    let radLat1 = lat1 * Math.PI / 180.0;
    let radLat2 = lat2 * Math.PI / 180.0;
    let a = radLat1 - radLat2;
    let b = lng1 * Math.PI / 180.0 - lng2 * Math.PI / 180.0;
    let s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) +
      Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
    s = s * 6378.137;// EARTH_RADIUS;
    s = Math.round(s * 10000) / 10000;
    return s;
  };

  render() {
    const circleStytle = {
      fillOpacity: 0.7,
      fillColor: '#4B9248',
      strokeWeight: 8,
      strokeColor: '#1196EE'
    };

    const styleC = {
      background: `url('http://icons.iconarchive.com/icons/paomedia/small-n-flat/1024/map-marker-icon.png')`,
      //background: `url('../../../../assets/testDrive/start.png')`,
      backgroundSize: 'contain',
      backgroundRepeat: 'no-repeat',
      backgroundPosition: 'center',
      width: '35px',
      height: '45px',
      color: '#000000',
      textAlign: 'center',
      lineHeight: '40px'
    };


    return (
      <Modal
        closable={true}
        title='行车轨迹'
        width="55%"
        style={{top: 16}}
        visible={this.props.visible}
        onCancel={() => this.onClose()}
        footer={[<Button key="back" type="primary" size="default" onClick={() => this.onClose()}>关闭</Button>]}
      >
        <div style={{width: '100%', height: '485px'}}>
          <Map
            //plugins={['OverView']}
            mapStyle={'fresh'}
            version={'1.4.2'}
            amapkey={'f992026da87e2f2063e7485244b8131b'}
            animateEnable={true}
            useAMapUI={true}
            zoom={this.state.zoomSize}
            expandZoomRange={true}
            center={this.state.mapCenter}
          >
            <Marker position={this.state.markerPosition1}>
              <div id='m1' style={styleC}>{this.state.value1}</div>
            </Marker>
            <Marker position={this.state.markerPosition2}>
              <div id='m2' style={styleC}>{this.state.value2}</div>
            </Marker>
            <Polyline
              style={circleStytle}
              path={this.state.linePath}
              lineJoin='round'
              bubble={true}
              showDir={true}/>
          </Map>
        </div>
      </Modal>
    );
  }
}

export default MapModel;
